/**
 * 工具函数
 */

//设置cookie
export const setCookie = (name,value,Days) => {
    var exp = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

export const getCookie = (key) =>{
    var arr,reg = RegExp('(^| )'+key+'=([^;]+)(;|$)');
    if (document.cookie.match(reg)) {
        arr = document.cookie.match(reg)
        return decodeURIComponent(arr[2]);
    }    
    else {
        return null;
    }
}


export const delCookie = (key) => {
    // 删除cookie
    var date = new Date();
    date.setTime(date.getTime() - 1);
    var delValue = getCookie(key);
    if (delValue != null) {
        document.cookie = key+'='+delValue+';expires='+date.toGMTString();
    }
}

//防抖
export const debounce = (func,wait,immediate) => {
    let timeout;
    return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout);
        if (immediate) {
            var callNow = !timeout;
            timeout = setTimeout(() => {
                timeout = null;
            }, wait)
            if (callNow) func.apply(context, args)
        }
        else {
            timeout = setTimeout(function(){
                func.apply(context, args)
            }, wait);
        }
    }
}

//节流
export const throttle = (func, wait) => {
    let previous = 0;
    return function() {
        let now = Date.now();
        let context = this;
        let args = arguments;
        if (now - previous > wait) {
            func.apply(context, args);
            previous = now;
        }
    }
}

export const getNowFormatDate = (data,type=1,symbel='-') => {
    let date = data ? new Date(data): new Date();
    let seperator1 = symbel;
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    let currentdate;
    switch (type) {
        case 1: 
            currentdate = year + seperator1 + month + seperator1 + strDate
            break;
        case 2: 
            currentdate = year + seperator1 + month
            break;
    }
    return currentdate;
}

//上个月
export const lastMonth = (date) => {
    let time = date ? new Date(date) : new Date()
    let year = time.getFullYear(), month = time.getMonth();
    if (month == 0) {
        month = 12;
        year = year - 1;
    }
    return year + '-' + (month > 9 ? month : ("0" + month)) 
}